<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-23
 * Time: 17:26
 */

namespace app\admin\service;

// 获取微信开放平台网站应用的相关数据
use think\facade\Config;

class WXWebAppData
{
    private $app_id = '';
    private $app_secret = '';

    public function __construct()
    {
        $this->app_id = get_wx_config('wx_web_app_app_id');
        $this->app_secret = get_wx_config('wx_web_app_app_secret');
    }

    /**
     * 通过code获取access_token
     * @param string $code
     * @return mixed
     */
    public function getWebAppAccessToken($code = '')
    {
        $url = Config::get('wx_web_app.code_to_access_token');
        $url = sprintf($url,
            $this->app_id,
            $this->app_secret,
            $code);

        return $this->requestWxServer($url, '获取access_token');
    }

    /**
     * 刷新access_token
     * @param string $refresh_token
     * @return mixed
     */
    public function refreshAccessToken($refresh_token = '')
    {
        $url = Config::get('wx_web_app.refresh_access_token');
        $url = sprintf($url,
            $this->app_id,
            $refresh_token);

        return $this->requestWxServer($url, '刷新access_token');
    }

    /**
     * 校验access_token是否有效
     * @param string $access_token
     * @return mixed
     */
    public function checkAccessToken($access_token = '')
    {
        $url = Config::get('wx_web_app.check_access_token');
        $url = sprintf($url,
            $access_token,
            $this->app_id);

        return $this->requestWxServer($url, '校验access_token');
    }

    /**
     * 获取用户个人信息
     * @param $access_token
     * @param string $openid
     * @return mixed
     */
    public function getUserInfo($access_token, $openid = '')
    {
        $url = Config::get('wx_web_app.get_user_info');
        $url = sprintf($url,
            $access_token,
            $openid);

        return $this->requestWxServer($url, '获取用户个人信息');
    }

    /**
     * 根据url地址请求微信服务器获取数据
     * @param string $url   请求地址
     * @param string $err_msg   当前请求所属错误信息
     * @return mixed
     */
    private function requestWxServer($url = '', $err_msg = '')
    {
        if (empty($url)) {
            throw new \Exception('请求的开放平台网站应用的url地址不能为空');
        }

        $request_data = curl_get($url);
        if (!$request_data) {
            throw new \Exception('[微信网站应用]请求数据发送错误，url:'.$url);
        }

        // 对数据进行处理
        $request_data = json_decode($request_data, true);

        // 判断数据是否有误（返回错误码）
        if (isset($request_data['errcode']) && $request_data['errcode'] != 0) {
            throw new \Exception('[微信网站应用]'.$err_msg.'失败，errcode:'.$request_data['errcode'].' errmsg:'.$request_data['errmsg']);
        }

        return $request_data;
    }
}